﻿using Microsoft.Win32;
using Prism.Commands;
using Prism.Events;
using Prism.Regions;
using Prism.Services.Dialogs;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model;
using SmartPlant.Model.Biz;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using SmartPlant.WinCore.Helper;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using Unity;

namespace SmartPlant.Modules.Base.ViewModels
{
    public class TemplateInputSettingViewModel : ListRegionViewModel<Report>
    {
        private int _templateType = 0;
        private DelegateCommand<string> _downloadFileCommand;
        private DelegateCommand<string> _uploadFileCommand;
        private DelegateCommand<object> _uploadAllFileCommand;
        private DelegateCommand  _deleteFileCommand;
        private ITemplateSettingService _templateSettingService;
        private readonly IEventAggregator _eventAggregator;

        public TemplateInputSettingViewModel(
            int templateType,
            IRegionManager regionManager,
            ITemplateSettingService templateSettingService,
            IUnityContainer unityContainer,
            IDialogService dialogService,
            IEventAggregator eventAggregator) :
            base(regionManager, unityContainer, dialogService)
        {
            _templateType = templateType;
            _templateSettingService = templateSettingService;
            _eventAggregator = eventAggregator;
        }

        public ICommand UploadAllFileCommand
        {
            get
            {
                if (_uploadAllFileCommand != null) return _uploadAllFileCommand;
                _uploadAllFileCommand = new DelegateCommand<object>(onUpLoadAllCommandAsync);
                return _uploadAllFileCommand;
            }
        }

        public ICommand UploadFileCommand
        {
            get
            {
                if (_uploadFileCommand != null) return _uploadFileCommand;
                _uploadFileCommand = new DelegateCommand<string>(onUpLoadCommandAsync);
                return _uploadFileCommand;
            }
        }

        public ICommand DownloadFileCommand
        {
            get
            {
                if (_downloadFileCommand != null) return _downloadFileCommand;
                _downloadFileCommand = new DelegateCommand<string>(onDownLoadCommandAsync);
                return _downloadFileCommand;
            }
        }

        public ICommand DeleteFileCommand
        {
            get
            {
                if (_deleteFileCommand != null) return _deleteFileCommand;
                _deleteFileCommand = new DelegateCommand (onDeleteFileCommandAsync);
                return _deleteFileCommand;
            }
        }

        private async void onDeleteFileCommandAsync()
        {
            if (SelectObj == null)
            {
                Dialog.ShowAltert("请先选择需要删除的模板！！！");
                return;
            }
            string proId = GlobalObject.CurrentProject.ProjId.ToString();
            var result = await _templateSettingService.DeleteTemplateFileAsync(proId, _templateType, SelectObj);
            if (result)
            {
                OnInitPage(null);//刷新页面内容
                _eventAggregator.GetEvent<TemplateChangedEvent>()
                                        .Publish((TemplateType)_templateType);//发布事件，参数为_templateType,索引导入模块有订阅
            }
        }

        private async void onDownLoadCommandAsync(string fileType)
        {
            if (SelectObj == null)
            {
                Dialog.ShowAltert("请先选择需要编辑的模板！！！");
                return;
            }
            string templatename = ".xlsx";
            string fileFilter = "Excel文件 *.xlsx|*.xlsx";
            if (fileType.ToLower() == "xml")
            {
                templatename = ".xml";
                fileFilter = "XML文件 *.xml|*.xml";
            }

            //templatename = SelectObj.Name + templatename;

            string proId = GlobalObject.CurrentProject.ProjId.ToString();

            try
            {
                var postObj = SelectObj.CloneObject();
                postObj.Name += templatename;

                var result = await _templateSettingService.GetTemplateFileAsync(proId, postObj);
                if (!result.succeeded)
                {
                    LoggerHelper.Current.Error(result.errors.ToString());
                    Dialog.ShowAltert(result.errors.ToString());
                    return;
                }
                var saveFileDialog = new SaveFileDialog
                {
                    Filter = fileFilter,
                    FileName = postObj.Name,
                };
                using var stream = result.data;
                if (saveFileDialog.ShowDialog() == true)
                {
                    var _fielPath = saveFileDialog.FileName;
                    await FileHelper.WriteFileStreamAsync(stream, _fielPath);
                    var rMessage = "下载模板文件到本地成功，请编辑后重新上传！！！";
                    Dialog.ShowAltert(rMessage);
                    return;
                }
            }
            catch (Exception x)
            {
                var xMessage = $"获取远程服务器数据失败：{x.Message}！！！";
                LoggerHelper.Current.Error(xMessage, x);
                Dialog.ShowAltert(xMessage);
            }
        }

        private async void onUpLoadCommandAsync(string fileType)
        {
            if (SelectObj == null)
            {
                Dialog.ShowAltert("请先选择需要上传的模板对象！！！");
                return;
            }

            string proId = GlobalObject.CurrentProject.ProjId.ToString();
            string templatename = ".xlsx";
            string fileFilter = "Excel文件 *.xlsx|*.xlsx";
            if (fileType.ToLower() == "xml")
            {
                templatename = ".xml";
                fileFilter = "XML文件 *.xml|*.xml";
            }
            templatename = SelectObj.Name + templatename;

            var openFileDialog = new OpenFileDialog
            {
                Filter = fileFilter,
            };

            if (openFileDialog.ShowDialog() == true)
            {
                try
                {
                    using Stream stream = openFileDialog.OpenFile();
                    var r = await _templateSettingService.UploadTemplateFileAsync(proId, _templateType, SelectObj.TemplatePath, stream, templatename);
                    if (r)
                        Dialog.ShowAltert("上传文件至远程服务器成功！！！");
                }
                catch (Exception x)
                {
                    var xMessage = $"上传文件至远程服务器失败：{x.Message}！！！";
                    LoggerHelper.Current.Error(xMessage, x);
                    Dialog.ShowAltert(xMessage);
                }
            }
        }

        private void onUpLoadAllCommandAsync(object obj)
        {
            Dialog.ShowDialog("TemplateInputSettingNew",
                new DialogParameters($"templateType={_templateType}"),
                d =>
                {
                    if (d.Result == ButtonResult.OK)
                    {
                        OnInitPage(null);
                        _eventAggregator.GetEvent<TemplateChangedEvent>()
                        .Publish((TemplateType)_templateType);
                    }
                });
        }

        protected override async void OnInitPage(object obj)
        {
            try
            {
                string proId = GlobalObject.CurrentProject.ProjId.ToString();
                var list = await _templateSettingService.GetTemplateLisAsync(proId, _templateType.ToString());
                DataList.Clear();
                DataList.AddRange(list);
            }
            catch (Exception x)
            {
                var xMessage = $"模板数据加载失败：{x.Message}！！！";
                LoggerHelper.Current.Error(xMessage, x);
                Dialog.ShowAltert(xMessage);
            }
        }
    }
}